package com.xhqgov.manage.controller;

import com.xhqgov.manage.util.CONST;
import com.xhqgov.manage.util.ClientMap;
import org.apache.log4j.Logger;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class BaseController extends CONST {
    private static final Logger LOGGER =Logger.getLogger(BaseController.class);
    @Resource
    protected WebApplicationContext context;
    @Resource
    protected HttpServletRequest request;
    @Resource
    protected HttpServletResponse response;
    /**
     * 获取sessionKey的对应对象
     * @param type
     * @return
     */
    protected <T> T getSessionKeyObject(Class<T> type)
    {
        return getSessionObject(SESSION_KEY, type);
    }


    /**
     * 根据key获取session中的对象
     *
     * @param <T>
     * @param key
     * @param type
     * @return
     */
    protected <T> T getSessionObject(String key, Class<T> type) {
        HttpSession session = request.getSession();
        if (session == null) {
            return null;
        } else {
            Object rs = session.getAttribute(key);
            if (rs == null) {
                return null;
            } else {
                return type.cast(rs);
            }
        }
    }


    /**
     * 重新定义链式操作
     * @return
     */
    protected ClientMap clientMap(){
        return new ClientMap();
    }

    /**
     * 保存session对象
     *
     * @param key
     * @param value
     */
    protected void setSessionObject(String key, Object value) {
        HttpSession session = request.getSession();
        if (session == null) {
            return;
        } else {
            session.setAttribute(key, value);
        }
    }

    /**
     * session失效
     */
    protected void sessionInvalidate(){
        HttpSession session = request.getSession();
        session.invalidate();
    }
}
